import storage from 'store';
import {
  loginByUsername,
  logout
} from '@/api/auth';
import {
  userInfo,
  getRole
} from '@/api/user';
import {
  ACCESS_TOKEN
} from '@/store/mutation-types';
import {
  welcome
} from '@/utils/util';

const user = {
  state: {
    // 统一配置分页的选择条数
    defaultPaginationOptions: [
      '5', '7', '10'
    ],
    // 统一配置分页的默认一页条数
    defaultPaginationPagesize: 10,
    welcome: '',
    avatar: '',
    roles: [],
    permissions: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, {
      name,
      welcome
    }) => {
      state.name = name;
      state.welcome = welcome;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_INFO: (state, info) => {
      state.info = info;
    }
  },

  actions: { // 登录
    Login({
      commit
    }, {
      username,
      password
    }) {
      return new Promise((resolve, reject) => {
        loginByUsername(username, password,'/api/login').then(result => {
          storage.set(ACCESS_TOKEN, result.data.token, 7 * 24 * 60 * 60 * 1000);
          commit('SET_TOKEN', result.data.token);
          resolve(result);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 获取用户信息
    GetInfo({
      commit
    }) {
      return new Promise((resolve, reject) => {
        // userInfo().then(response => {
        //   console.log(response)
        // });
        getRole().then(response => {
          if (response.code == 200 && response.data) {
            const result = response.data;
            let {
              roleId,
              roleName,
              userId,
              userName,
              roleCode
            } = {
              ...result
            };
            commit('SET_ROLES', {
              roleId,
              roleName,
              userId,
              userName,
              roleCode
            });
            commit('SET_PERMISSIONS', result.resourceList);
            commit('SET_INFO', result);

            commit('SET_NAME', {
              name: result.userName,
              welcome: welcome()
            });
            // commit('SET_AVATAR', result.avatar);

            resolve(result);
          } else {
            reject(new Error('获取用户信息失败'));
          }
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    Logout({
      commit,
      state
    }) {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      commit('SET_PERMISSIONS', []);
      storage.remove(ACCESS_TOKEN);
      location.reload();
    }
  }
};

export default user;